package cn.itcast.service.impl;

import cn.itcast.dao.MenuDao;
import cn.itcast.dao.PermissionDao;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.pojo.Permission;
import cn.itcast.service.MenuService;
import cn.itcast.service.PermissionService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;


    /**
     * 分页查询权限管理列表
     * @param queryPageBean 查询条件
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        //开启分页查询
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //根据条件分页查询检查项信息
        Page<Permission> page = permissionDao.findPage(queryPageBean.getQueryString());
        //构建分页数据返回
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 增加权限
     * @param permission 权限具体信息
     * @return
     */
    @Override
    public Boolean handleAdd(Permission permission) {
        return permissionDao.handleAdd(permission) > 0;
    }





    /**
     * 根据id查询单条权限详情
     * @param id 当前权限id
     * @return
     */
    @Override
    public Permission handleUpdate(Integer id) {
        return permissionDao.findById(id);
    }



    /**
     * 编辑权限
     * @param permission 权限具体信息
     * @return
     */
    @Override
    public Boolean handleEdit(Permission permission) {
        return permissionDao.handleEdit(permission) > 0;
    }



    /**
     * 根据id删除权限
     * @param id 当前权限id
     * @return
     */
    @Override
    public Boolean handleDelete(Integer id) {
        return permissionDao.handleDelete(id) > 0;
    }



    /**
     * 查询所有权限
     * @return
     */
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    /**
     * 查询菜单关联的权限
     * @param menuIds 菜单id集合
     * @return
     */
    @Override
    public List<Permission> findMenuAssociationPermission(int[] menuIds) {
        List<Permission> list = new ArrayList<>();

        //查询菜单对应的权限id
        List<Integer> list1 = new ArrayList<>();
        for (int i = 0; i < menuIds.length; i++) {
            List<Integer> list2 = menuDao.handleUpdatePermissions(menuIds[i]);
            list1.addAll(list2);
        }
        System.out.println("100 = ======" + list1);

        for (Integer id : list1) {
            //然后根据权限id，查询权限的具体信息
            Permission permission = permissionDao.findMenuAssociationPermission(id);
            list.add(permission);
        }
        return list;
    }
}
